<?php

    if(!defined('BASEPATH'))
        exit('No direct script access allowed');

    /*
     * Main rentacar platform class
     * 
     */

    class Rentacar extends CI_Controller
    {

        var $data;

        function __construct()
        {
            parent::__construct();
            define("RENTACARPROFILE", "PRODUCTION");

            $this->load->library('rest', array(
                'server' => REST_URL_RENTACAR
            ));
            $this->data['hosting']=HOST_URL_RENTACAR;
            $this->load->library('session');
            $this->load->library('template');
            $this->load->library('rentacar/booking_error');
            $this->load->library('rentacar/booking_session');
            $this->load->library('rentacar/booking_prices');

            $this->load->helper('timemaker');
            $this->load->helper('calculate_days');
            $this->load->helper('day_price');
            $this->load->helper('number');
            $this->load->helper('gallery');
            $this->load->helper('urlify');
            $this->load->helper('clean_html');

            // load language file
            $this->lang->load ( 'common' );
            $this->lang->load('rentacar');

            //$this->output->enable_profiler(TRUE);

            require_once('urlify.php');
            $this->data['page']='rentacar';
            $this->load->model('cms_pro', 'cms');
            $this->load->library('translate', array('lang' => $this->lang->lang()));

            //echo $this->lang->lang();
            //$this->load->library('translate', array('lang' => 'me'));

            $this->template->set_view("rentacar");

            // Do caching
            $this->load->driver('cache', array('adapter' => 'file')); // za uklucuvanje na kes mogucnosti

            $cache_file1=$this->crate_cache_filename(array('af1' => 'af1'), 'action_footer_1');
            $cache_file2=$this->crate_cache_filename(array('af2' => 'af2'), 'action_footer_2');

            if((!$this->data['action_footer_1']=$this->cache->get($cache_file1)) || (!$this->data['action_footer_2']=$this->cache->get($cache_file2)))
            {
                $this->firephp->log($cache_file1);
                $this->firephp->log($cache_file2);

                $this->data['action_footer_1']=$this->rest->get('action1', NULL, 'json');
                $this->data['action_footer_2']=$this->rest->get('action2', NULL, 'json');

                $this->cache->save($cache_file1, $this->data['action_footer_1'], 300);
                $this->cache->save($cache_file2, $this->data['action_footer_2'], 300);
            }



            if(RENTACARPROFILE == "DEVELOPMENT"):
                log_message('error', 'rentacar -> construct');
                $this->firephp->log($this->booking_session->get_all_data());
            endif;

        }

        function index()
        {
            if(RENTACARPROFILE == "DEVELOPMENT"):
                log_message('error', 'rentacar -> index');
            endif;
            redirect(base_url('rentacar/initialize'));

        }

        /*
         * Rentacar homepage (destroy session, get location from service )
         * 
         */

        function home()
        {

            $this->data['locations']=$this->rest->get('locations', NULL, 'json');
            $this->data['method']='home';

            $params=array('lang' => $this->lang->lang());

            $cache_file1=$this->crate_cache_filename($params, 'action_1');
            $cache_file2=$this->crate_cache_filename($params, 'action_2');

            if((!$this->data['action_1']=$this->cache->get($cache_file1)) || (!$this->data['action_2']=$this->cache->get($cache_file2)))
            {
                $this->firephp->log($cache_file1);
                $this->firephp->log($cache_file2);

                $this->data['action_1']=$this->rest->get('action1', $params, 'json');
                $this->data['action_2']=$this->rest->get('action2', $params, 'json');

                $this->cache->save($cache_file1, $this->data['action_1'], 300);
                $this->cache->save($cache_file2, $this->data['action_2'], 300);
            }

            shuffle($this->data['action_1']);
            shuffle($this->data['action_2']);

            if(RENTACARPROFILE == "DEVELOPMENT"):
                log_message('error', 'rentacar -> home');
                $this->firephp->log($this->booking_session->get_all_data());
            //$this->firephp->log($this->data['action_1'][0]);
            endif;

            //$this->firephp->log($this->data['action_1']);
            //$this->firephp->log($this->data['action_2']);
			$this->data['title']=lang('title-home');
			$this->data['description']=lang('description-home');

            $this->template->load('rentacar/home', $this->data);

        }

        function initialize()
        {
            $this->session->sess_destroy();
            redirect(base_url('rentacar/home'));

        }

        /*
         * List of availiable cars (create session data and prices for step_2)
         *  
         */

        function available_fleet()
        {
            //print_r($_POST);
            // Get locations,
            // Create session from Search Module, booking_session->step_2
            $locations=$this->_getLocations();

            // Search available fleet
            $post=array(
                'dateTimeFrom' => $this->booking_session->get('pickup_date').' '.$this->booking_session->get('fullfrom'),
                'dateTimeTo' => $this->booking_session->get('return_date').' '.$this->booking_session->get('fullto'),
                'lang' => $this->lang->lang()
            );

            $cache_file=$this->crate_cache_filename($post, 'available_fleet');

            if(!$response=$this->cache->get($cache_file))
            {
                $this->firephp->log($cache_file);
                $response=$this->rest->post('available_cars', $post, 'json');

                $this->cache->save($cache_file, $response, 300);
            }



            $this->firephp->log($response);

            //print_r($response);
            // DONE: DayFrom15price throws error
            if($this->booking_error->response_check($response))
            {

                // Calculate and set number of days
                $this->data['car_list']=$response;
                $this->data['no_days']=calculateDays($post['dateTimeFrom'], $post['dateTimeTo']);
                $this->booking_session->set('no_days', $this->data['no_days']);

                // Calculate location ( pickup and return ) prices
                $this->booking_prices->step_2();

                $this->data['locations']=$locations;
                $this->data['method']='available_fleet';

                if(RENTACARPROFILE == "DEVELOPMENT"):
                    log_message('error', 'rentacar -> available_fleet');
                    $this->firephp->log($this->booking_session->get_all_data());
                //$this->firephp->log($this->data);
                endif;

				$this->data['title']=lang('title-search');
				$this->data['description']=lang('description-search');

                $this->template->load('rentacar/search', $this->data);
            }
            else
            {
                $this->rest_error($response);
            }

            //$this->_showNav();

        }

        /*
         * List all cars
         *  
         */

        function browse_fleet()
        {
            // Get locations,
            $this->data['locations']=$this->rest->get('locations', NULL, 'json');

            $params=array('lang' => $this->lang->lang());

            $cache_file=$this->crate_cache_filename($params, 'browse_fleet');

            if(!$response=$this->cache->get($cache_file))
            {
                $this->firephp->log($cache_file);
                $response=$this->rest->get('all_cars', $params, 'json');

                $this->cache->save($cache_file, $response, 300);
            }


            //print_r($response);
            // DONE: DayFrom15price throws error
            if($this->booking_error->response_check($response))
            {

                if(isset($_GET['type'])):
                    $response=$this->_filter_response($response, $_GET['type']);
                endif;

                $this->data['car_list']=$response;
                $this->data['method']='browse_fleet';

                if(RENTACARPROFILE == "DEVELOPMENT"):
                    log_message('error', 'rentacar -> browse_fleet');
                    $this->firephp->log($this->booking_session->get_all_data());
                //$this->firephp->log($this->data);
                endif;

				$this->data['title']=lang('title-search');
				$this->data['description']=lang('description-search');

                $this->template->load('rentacar/search', $this->data);
            }
            else
            {
                $this->rest_error($response);
            }

            //$this->_showNav();

        }

        public function crate_cache_filename($data, $mehod)
        {
            $filename='rentacar_'.$mehod.'';

            foreach($data as $key => $value):
                if(is_array($value))
                {
                    foreach($value as $value)
                    {
                        $filename.='_'.$key.'-'.$value;
                    }
                }
                else
                {
                    $filename.='_'.$key.'-'.$value;
                }
            endforeach;

            return $filename;

        }

        private function _filter_response($response, $type)
        {
            $type=strtolower($type);
            $cnt=count($response);
            for($i=0; $i < $cnt; $i++):
                $name=strtolower($response[$i]->name);
//                $this->firephp->log($name);
//                $this->firephp->log($type);


                if(strpos($name, $type) !== false)
                {
                    //$this->firephp->log('ok');
                }
                else
                {
                    if($type == 'valksfagen')
                    {
                        if(strpos($name, 'vw') !== false)
                        {
                            //$this->firephp->log('ok');
                        }
                        else
                        {
                            unset($response[$i]);
                        }
                    }
                    else
                    {
                        unset($response[$i]);
                    }
                }
            endfor;

            return $response;

        }

        /*
         * Get car details with pictures and video
         * Set car_id and day_price session, unset extras if different car_id
         * Calculate prices for booking days
         * 
         * @param $href 
         */

        function car_details($href)
        {
            // Check if first session data pickup_loc_id is set. Redirect if False 
            if(!$this->session->userdata('pickup_loc_id'))
            {
                $this->browse_car_details($href);
                return;
            }

            $car_ID=idFromUrl($href, '-');
            $post=array(
                'id' => $car_ID,
                'lang' => $this->lang->lang()
            );
            $response=$this->rest->post('get_car', $post, 'json');
            // Check service response for Car
            if($this->booking_error->response_check($response))
            {

                $this->data['car']=$response[0];
                // Set car_id and day_price session, unset extras if different car_id
                $this->booking_session->step_3($response[0]);
                // Calculate prices for booking days
                $this->booking_prices->step_3($response[0]);

                // Get images and Video
                $images=$this->rest->post('get_car_images', $post, 'json');
                $video=$this->rest->post('get_car_video', $post, 'json');

                // Check service response for Images and Vido
                if($this->booking_error->response_check($images))
                {
                    if($images)
                    {
                        $this->data['images']=$images;
                    }
                }
                else
                {
                    $this->rest_error($response);
                }

                if($this->booking_error->response_check($video))
                {
                    if($video)
                    {
                        $this->data['video']=$video[0];
                    }
                }
                else
                {
                    $this->rest_error($response);
                }

                // Get locations
                $locations=$this->rest->get('locations', NULL, 'json');
                if($locations)
                {
                    $this->data['locations']=$locations;
                }
                else
                {
                    echo 'Error: Location on car_details method';
                }

                $this->data['load_lightbox']=TRUE;
                $this->data['method']='car_details';

                if(isset($_POST['redirect_checkout']) && $_POST['redirect_checkout'] == 1)
                {

                    redirect(base_url('rentacar/checkout/'.$href));
                }
                else
                {
                    if(RENTACARPROFILE == "DEVELOPMENT"):
                        log_message('error', 'rentacar -> car_details');
                        $this->firephp->log($this->booking_session->get_all_data());
                    endif;

					$pieces=explode(" ", $this->data['car']->name);
					unset($pieces[0]);
					$carName = join(' ', $pieces);
					
					$this->data['title']= str_replace('{|0|}', $carName, lang('title-details'));	
					$this->data['description']= clean_html($this->data['car']->description);
					$this->data['canonical'] = base_url('rentacar/'.urlify::filter($this->data['car']->name).'-'.$this->data['car']->id);					

                    $this->template->load('rentacar/car_details', $this->data);
                }
            }
            else
            {
                $this->rest_error($response);
            }
            //$this->_showNav();

        }

        /*
         * Get car details with pictures and video
         * Set car_id and day_price session, unset extras if different car_id
         * Calculate prices for booking days
         * 
         * @param $href 
         */

        function browse_car_details($href, $not_available=FALSE)
        {
            if($not_available)
            {
                $this->data['not_available']=$not_available;
            }

            $car_ID=idFromUrl($href, '-');
            $post=array(
                'id' => $car_ID,
                'lang' => $this->lang->lang()
            );
            $response=$this->rest->post('get_car', $post, 'json');
            // Check service response for Car
            if($this->booking_error->response_check($response))
            {

                $this->data['car']=$response[0];
                // Set car_id and day_price session, unset extras if different car_id
                // Check if different car is selected and delete accessories session
                if($this->booking_session->get('car_id') != $response[0]->id)
                {
                    $this->booking_session->unsetData('extras');
                    //$this->_CI->firephp->log('unset extras');
                }

                //set car_id in session
                $this->booking_session->set('car_id', $response[0]->id);

                // Calculate prices for booking days
                $this->booking_session->set('tot_price', 0);

                // Get images and Video
                $images=$this->rest->post('get_car_images', $post, 'json');
                $video=$this->rest->post('get_car_video', $post, 'json');

                // Check service response for Images and Vido
                if($this->booking_error->response_check($images))
                {
                    if($images)
                    {
                        $this->data['images']=$images;
                    }
                }
                else
                {
                    $this->rest_error($response);
                }

                if($this->booking_error->response_check($video))
                {
                    if($video)
                    {
                        $this->data['video']=$video[0];
                    }
                }
                else
                {
                    $this->rest_error($response);
                }

                // Get locations
                $locations=$this->rest->get('locations', NULL, 'json');
                if($locations)
                {
                    $this->data['locations']=$locations;
                }
                else
                {
                    echo 'Error: Location on car_details method';
                }

                if(RENTACARPROFILE == "DEVELOPMENT"):
                    log_message('error', 'rentacar -> browse_car_details');
                    $this->firephp->log($this->booking_session->get_all_data());
                endif;

                $this->data['load_lightbox']=TRUE;
                $this->data['method']='browse_car_details';
				
				$pieces=explode(" ", $this->data['car']->name);
				unset($pieces[0]);
				$carName = join(' ', $pieces);
				
				$this->data['title']= str_replace('{|0|}', $carName, lang('title-details'));	
				$this->data['description']= clean_html($this->data['car']->description);
				$this->data['canonical'] = base_url('rentacar/'.urlify::filter($this->data['car']->name).'-'.$this->data['car']->id);		
					
                $this->template->load('rentacar/car_details', $this->data);
            }
            else
            {
                $this->rest_error($response);
            }
            //$this->_showNav();

        }

        /*
         * User change pickup and return locations, prices or times on car_details page
         * Create session from Search Module
         * Calculate location ( pickup and return ) prices
         * 
         * @param $href 
         */

        // DONE: Get car quote resets value of datepickers when submited
        function get_car_quote($href)
        {
            if($this->input->post('browse_car_details'))
            {
                // Create session from Search Module, booking_session->step_2
                $locations=$this->_getLocations();

                $car_ID=idFromUrl($href, '-');

                // Search if car is availiable
                $post=array(
                    'dateTimeFrom' => $this->booking_session->get('pickup_date').' '.$this->booking_session->get('fullfrom'),
                    'dateTimeTo' => $this->booking_session->get('return_date').' '.$this->booking_session->get('fullto'),
                    'car_id' => $car_ID,
                    'lang' => $this->lang->lang()
                );

                // is availiable 
                // return 1 if car is booked ( not available )
                // return 0 if car is available
                $response=$this->rest->post('isAvailiable', $post, 'json');
                if($response->available == 1)
                {
                    $this->browse_car_details($href, 'Car is not available in this period.');
                    return;
                }
            }

            // Check if first session data pickup_loc_id is set. Redirect if False 
            $this->booking_session->check_session();

            // Get locations,
            // Create session from Search Module, booking_session->step_2
            $locations=$this->_getLocations();

            // Calculate numberOdDays
            $dateTimeFrom=$this->booking_session->get('pickup_date').' '.$this->booking_session->get('fullfrom');
            $dateTimeTo=$this->booking_session->get('return_date').' '.$this->booking_session->get('fullto');
            $this->data['no_days']=calculateDays($dateTimeFrom, $dateTimeTo);
            $this->booking_session->set('no_days', $this->data['no_days']);

            // Calculate location ( pickup and return ) prices
            $this->booking_prices->step_2();

            //load car_details page
            $this->car_details($href);

        }

        /*
         * Go to checkout page
         * 
         * @param 
         */

        function checkout($href)
        {

            // Check if first session data pickup_loc_id is set. Redirect if False 
            $this->booking_session->check_session();
            //$this->firephp->log($this->session->all_userdata());

            $car_ID=idFromUrl($href, '-');
            $post=array(
                'id' => $car_ID,
                'lang' => $this->lang->lang()
            );
            $response=$this->rest->post('get_car', $post, 'json');
            // Check service response for Car
            if($this->booking_error->response_check($response))
            {

                $this->data['car']=$response[0];
                // Set car_id and day_price session, unset extras if different car_id
                $this->booking_session->step_3($response[0]);
                // Calculate prices for booking days
                $this->booking_prices->step_3($response[0]);

                // Get car accessories
                $post=array(
                    'id' => $this->booking_session->get('car_id'),
                    'lang' => $this->lang->lang()
                );
                $accessories=$this->rest->post('accessories', $post, 'json');

                if($this->booking_error->response_check($accessories))
                {
                    $this->data['accessories']=$accessories;
                    $this->booking_prices->extras($accessories, $response[0]);

                    // If extras selected by post, get extras info from service and create html
                    $html=$this->_extrasHtml(
                            $this->booking_session->get('car_id'), $response[0]);

                    $this->data['extras_html']=$html;
                }
                else
                {
                    $this->rest_error($response);
                }

                $this->data['method']='checkout';
                $this->data['terms']=$this->translate->trans_row_array($this->cms->get_post(112));


                if(RENTACARPROFILE == "DEVELOPMENT"):
                    log_message('error', 'rentacar -> checkout');
                    $this->firephp->log($this->booking_session->get_all_data());
                //$this->firephp->log($this->data);
                endif;

                $this->template->load('rentacar/checkout', $this->data);
            }
            else
            {
                $this->rest_error($response);
            }
            //$this->_showNav();

        }

        /*
         * Set customer form
         * 
         * @param $_POST
         */

        function checkout_customer()
        {
            // Set customer in booking session
            $this->booking_session->set('cust_name', urlencode($this->input->post('name')));
            $this->booking_session->set('cust_email', urlencode($this->input->post('email')));
            $this->booking_session->set('cust_phone', urlencode($this->input->post('phone')));
            $this->booking_session->set('cust_note', urlencode($this->input->post('note')));
            $this->booking_session->set('cust_terms', $this->input->post('terms'));
            $this->booking_session->set('cust_address1', $this->input->post('address'));
            $this->booking_session->set('cust_town_city', $this->input->post('city'));
            $this->booking_session->set('cust_zip_code', $this->input->post('zip'));
            $this->booking_session->set('cust_country', $this->input->post('country'));

            $post=array(
                'session' => $this->booking_session->get_all_data(),
                'lang' => $this->lang->lang()
            );

            //$this->firephp->log($post);

            $response=$this->rest->post('process_booking', $post, 'json');
            // Check service response for Write booking
            if($this->booking_error->response_check($response))
            {
                $this->booking_session->set('carbooking_id', $response[0]->id);
                if(RENTACARPROFILE == "DEVELOPMENT"):
                    log_message('error', 'rentacar -> checkout_customer');
                    $this->firephp->log($this->booking_session->get_all_data());
                endif;

                echo json_encode(array('response' => TRUE, 'msg' => 'OK', 'json' => $response[0]));
            }
            else
            {
                $this->rest_error($response);
            }

        }

        /*
         * Checkout show order
         * 
         * @param orderID
         */

        function checkout_show_order($orderID)
        {
            //echo 'Checkout 3: orederID: '.$orderID;
            $post=array(
                'carbooking_id' => $orderID,
                'lang' => $this->lang->lang()
            );

            $response=$this->rest->post('show_order', $post, 'json');
            // Test booking info response from service
            if($this->booking_error->response_check($response[0][0]))
            {
                $this->data['order']=$response[0][0];

                $post=array(
                    'id' => $this->data['order']->carid,
                    'lang' => $this->lang->lang()
                );
                $car_response=$this->rest->post('get_car', $post, 'json');
                // Check service response for Car
                if($this->booking_error->response_check($response))
                {
                    $this->data['car']=$car_response[0];
                }
                else
                {
                    $this->rest_error($response);
                }

                $order_extras=$this->booking_error->response_check($response[1]);
                if($order_extras)
                {
                    // If extras selected by post, get extras info from service and create html
                    $html=$this->_extrasHtml($this->booking_session->get('car_id'), $car_response[0]);
                    $this->data['extras_html']=$html;
                }

                if(RENTACARPROFILE == "DEVELOPMENT"):
                    log_message('error', 'rentacar -> checkout_show_order');
                    $this->firephp->log($this->booking_session->get_all_data());
                endif;

                $this->data['method']='checkout';
                
                $this->template->load('rentacar/checkout_3', $this->data);
            }
            else
            {
                $this->rest_error($response);
            }

            //$this->_showNav();

        }

        /*
         * Set extras / optional accessories / bonus equipment
         * 
         * @param $_POST
         */

        function set_extras()
        {

            // set session for extars
            $this->booking_session->extras($this->input->post('extras'));
            $extras=$this->booking_session->get('extras');

            // Here we reset prices to step_3 if no extras are posted
            $post=array(
                'id' => $this->booking_session->get('car_id'),
                'lang' => $this->lang->lang()
            );
            $car_response=$this->rest->post('get_car', $post, 'json');
            $this->booking_prices->extras(NULL, $car_response[0]);

            // If extras selected by post, get extras info from service and create html
            $html=$this->_extrasHtml($this->booking_session->get('car_id'), $car_response[0]);

            echo json_encode(array('action' => TRUE, 'html' => $html, 'tot_price' => $this->booking_session->get('tot_price')));

        }

        /*
         * Extras html, create extras html and set booking_prices for extras
         * 
         * @param $extras
         * @param $car_ID
         * @param $car_response
         */

        function _extrasHtml($car_ID, $car_response)
        {
            $html='';

            $post=array(
                'id' => $car_ID,
                'lang' => $this->lang->lang()
            );

            $extras=$this->booking_session->get('extras');

            if(count($extras) > 0 && $extras != FALSE):

                $response=$this->rest->post('accessories', $post, 'json');
                //$this->firephp->log($response);
                if($this->booking_error->response_check($response))
                {
                    foreach($response as $row1)
                    {

                        //$this->firephp->log($extras);
                        foreach($extras as $val)
                        {

                            if($row1->id == $val):

                                $data=array(
                                    'data_id' => $row1->id,
                                    'desc' => $row1->type,
                                    'text' => $row1->price.' &euro; / '.lang('rentacar.day')
                                );
                                $html.= $this->load->view('rentacar/parts/checkout_list_item_extras', $data, TRUE);

                            endif;
                        }
                    }

                    $this->booking_prices->extras($response, $car_response);
                }else
                {
                    $this->rest_error($response);
                }
            endif;

            return $html;

        }

        /*
         * Check for errors on service reponse, echos error
         * 
         * @param $object
         */

        function rest_error($object)
        {
            switch($this->booking_error->getFlag())
            {
                case 'error':
                    print_r($this->booking_error->getError());
                    break;
                case 'numrows':
                    //$this->firephp->log( 'Num rows: '.$this->booking_error->getNumrows() );
                    break;
                case 'info':
                    print_r($this->booking_error->getInfo());
                    break;
            }

        }

        /*
         * Get locations from service and create session from Search Module
         * 
         */

        function _getLocations()
        {
            // Create session from Search Module Rentacar
            if($this->input->post('pickup_loc_id') || $this->booking_session->get('pickup_loc_id'))
            {
                $locations=$this->rest->get('locations', NULL, 'json');
                if($locations)
                {
                    $this->booking_session->step_2($locations);
                    return $locations;
                }
                else
                {
                    echo 'Error: Location on availibale_fleet method';
                }
            }
            else
            {
                redirect(base_url());
            }

        }

        function _showNav()
        {
            $html='<ul>';
            $html .= '<li><a href="'.base_url("test_rentacar/home").'">Home / Locations</a></li>';
            $html .= '<li><a href="'.base_url("test_rentacar/available_fleet").'">Available Fleet</a></li>';
            $html .= '<li><a href="'.base_url("test_rentacar/checkout/daewoo-kalos-43").'">Checkout daewoo-kalos-43</a></li>';
            $html .= '<li><a href="'.base_url("rentacar/home").'">Go to website</a></li>';
            $html .= '</ul>';
            echo $html;

        }

    }

?>
